-- ============================================
-- ROCKET RUNNER - plateforme physique controlee par manette Create
-- Gravite, saut, ennemis a ecraser, pieces a collecter, bordure
-- clignotante, ~16 FPS, musique de fond + bruitages (Speaker).
-- Nécessite : Advanced Computer + Advanced Monitor + Redstone
--             Integrator + Speaker (optionnel mais recommande)
-- ============================================

-- === A CONFIGURER : quelle face de l'Integrator recoit quel bouton ===
local BUTTON_SIDES = {
    UP    = "top",     -- non utilise pour le moment (physique = pas de vol)
    DOWN  = "bottom",  -- non utilise pour le moment
    LEFT  = "left",
    RIGHT = "right",
    A     = "front",   -- saut
}

local FRAME_TIME = 0.05       -- ~20 FPS : plafond reel de CC:Tweaked (cale sur les
                                -- ticks Minecraft, 30 FPS n'est pas atteignable en pratique)
local GRAVITY = 1              -- acceleration verticale (cellules/tick^2)
local MAX_FALL_SPEED = 3
local JUMP_VELOCITY = -4
local STOMP_BOUNCE = -3
local MOVE_SPEED = 1            -- cellules par tick en mouvement continu
local INVINCIBLE_TIME = 1.2
local SPAWN_ENEMY_EVERY = 22    -- ticks entre 2 ennemis
local SPAWN_COIN_EVERY = 30
local GROUND_ROWS = 2

local PLAYER_W, PLAYER_H = 5, 3
local ENEMY_W, ENEMY_H = 3, 2

local integrator = peripheral.find("redstoneIntegrator")
if not integrator then
    error("Aucun Redstone Integrator trouve ! Colle-en un (Advanced Peripherals) relie au computer.")
end

local speaker = peripheral.find("speaker")  -- optionnel, l'anim marche sans

local mon = peripheral.find("monitor")
local monitorAttempts = 0
while not mon and monitorAttempts < 20 do
    sleep(0.25)
    mon = peripheral.find("monitor")
    monitorAttempts = monitorAttempts + 1
end
if not mon then
    error("Aucun monitor trouve apres plusieurs tentatives ! Verifie qu'un Advanced Monitor est bien connecte.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

local function fillArea(x1, y1, x2, y2, bg)
    term.setBackgroundColor(bg)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", math.max(0, x2 - x1 + 1)))
    end
end

-- === SONS (musique de fond en boucle + bruitages) ===
local MELODY = {
    -- phrase 1 (montante, entrainante)
    { note = "harp", pitch = 8,  dur = 0.16 },
    { note = "harp", pitch = 10, dur = 0.16 },
    { note = "harp", pitch = 12, dur = 0.16 },
    { note = "bell", pitch = 15, dur = 0.32 },
    { note = "harp", pitch = 12, dur = 0.16 },
    { note = "harp", pitch = 10, dur = 0.16 },
    { note = "harp", pitch = 8,  dur = 0.32 },
    -- phrase 2 (variation)
    { note = "harp", pitch = 12, dur = 0.16 },
    { note = "harp", pitch = 15, dur = 0.16 },
    { note = "harp", pitch = 17, dur = 0.16 },
    { note = "bell", pitch = 19, dur = 0.32 },
    { note = "harp", pitch = 17, dur = 0.16 },
    { note = "harp", pitch = 15, dur = 0.16 },
    { note = "harp", pitch = 12, dur = 0.32 },
    -- phrase 3 (refrain, plus enleve)
    { note = "bell", pitch = 19, dur = 0.16 },
    { note = "harp", pitch = 19, dur = 0.16 },
    { note = "harp", pitch = 17, dur = 0.16 },
    { note = "harp", pitch = 15, dur = 0.16 },
    { note = "bell", pitch = 22, dur = 0.40 },
    { note = "harp", pitch = 17, dur = 0.16 },
    { note = "harp", pitch = 15, dur = 0.16 },
    { note = "harp", pitch = 12, dur = 0.16 },
    { note = "bell", pitch = 15, dur = 0.40 },
    -- phrase 4 (finale, retour au calme avant de boucler)
    { note = "harp", pitch = 12, dur = 0.16 },
    { note = "harp", pitch = 10, dur = 0.16 },
    { note = "harp", pitch = 8,  dur = 0.16 },
    { note = "bass", pitch = 6,  dur = 0.50 },
}

local musicOn = true
local function playMusic()
    if not speaker then return end
    while musicOn do
        for _, n in ipairs(MELODY) do
            speaker.playNote(n.note, 0.7, n.pitch)
            sleep(n.dur)
            if not musicOn then return end
        end
    end
end

local function sfxJump()
    if not speaker then return end
    speaker.playNote("bit", 1, 8)
    speaker.playNote("bit", 1, 14)
end

local function sfxCoin()
    if not speaker then return end
    speaker.playNote("bell", 1, 20)
end

local function sfxStomp()
    if not speaker then return end
    speaker.playNote("bass", 1, 6)
end

local function sfxHit()
    if not speaker then return end
    speaker.playNote("bass", 1, 2)
    speaker.playNote("bass", 1, 1)
end

-- === BORDURE ANIMEE / CLIGNOTANTE ===
local function drawStripedBorder(phase)
    for x = 1, w do
        local base = ((x + 1) % 4 < 2)
        local col
        if phase then
            col = base and colors.yellow or colors.white
        else
            col = base and colors.red or colors.yellow
        end
        term.setBackgroundColor(col)
        term.setCursorPos(x, 1); term.write(" ")
        term.setCursorPos(x, h); term.write(" ")
    end
    for y = 1, h do
        local base = ((y + 1) % 4 < 2)
        local col
        if phase then
            col = base and colors.yellow or colors.white
        else
            col = base and colors.red or colors.yellow
        end
        term.setBackgroundColor(col)
        term.setCursorPos(1, y); term.write(" ")
        term.setCursorPos(w, y); term.write(" ")
    end
end

-- === ZONE DE JEU ===
local playTop, playBottom = 4, h - 2
local playLeft, playRight = 2, w - 1
local groundTop = playBottom - GROUND_ROWS + 1
local skyBottom = groundTop - 1
local groundStandY = groundTop - PLAYER_H  -- position Y (haut du sprite) quand au sol

-- === DECOR ===
local sunX, sunY = playRight - 3, playTop
local BUSH_COUNT = math.max(2, math.floor((playRight - playLeft) / 12))
local bushes = {}
for i = 1, BUSH_COUNT do
    bushes[i] = playLeft + math.floor((i - 0.5) * (playRight - playLeft) / BUSH_COUNT)
end

local function drawSun()
    fillArea(sunX, sunY, sunX + 1, sunY + 1, colors.yellow)
    -- petits rayons pour donner du relief
    term.setBackgroundColor(colors.orange)
    term.setCursorPos(sunX - 1, sunY); term.write(" ")
    term.setCursorPos(sunX + 2, sunY + 1); term.write(" ")
    term.setCursorPos(sunX, sunY - 1); term.write(" ")
end

local function drawBushes()
    term.setBackgroundColor(colors.green)
    for _, bx in ipairs(bushes) do
        term.setCursorPos(bx - 1, groundTop - 1); term.write("   ")
    end
end

local clouds = {}
local function initClouds()
    clouds = {}
    local count = math.max(2, math.floor((playRight - playLeft) / 20))
    for i = 1, count do
        clouds[i] = { x = math.random(playLeft, playRight), y = math.random(playTop, math.max(playTop, skyBottom - 2)) }
    end
end

local function updateClouds()
    for _, c in ipairs(clouds) do
        c.x = c.x - 1
        if c.x < playLeft - 3 then
            c.x = playRight + 2
            c.y = math.random(playTop, math.max(playTop, skyBottom - 2))
        end
    end
end

local function drawClouds()
    term.setBackgroundColor(colors.white)
    for _, c in ipairs(clouds) do
        for dx = -1, 1 do
            local x = c.x + dx
            if x >= playLeft and x <= playRight then
                term.setCursorPos(x, c.y)
                term.write(" ")
            end
        end
    end
end

local function drawScenery()
    -- ciel en degrade (plus clair en haut, plus fonce vers l'horizon)
    local midY = math.floor((playTop + skyBottom) / 2)
    fillArea(playLeft, playTop, playRight, midY, colors.lightBlue)
    fillArea(playLeft, midY + 1, playRight, skyBottom, colors.cyan)
    drawSun()
    drawClouds()
    -- herbe texturee (alternance de teintes selon la colonne)
    for x = playLeft, playRight do
        term.setBackgroundColor((x % 3 == 0) and colors.lime or colors.green)
        for y = groundTop, playBottom do
            term.setCursorPos(x, y)
            term.write(" ")
        end
    end
    drawBushes()
end

-- === POLICE PIXEL-ART (chiffres) POUR LE GROS SCORE DANS LE CIEL ===
local DIGIT_FONT = {
    ["0"] = { "01110", "10001", "10001", "10001", "01110" },
    ["1"] = { "00100", "01100", "00100", "00100", "01110" },
    ["2"] = { "01110", "10001", "00010", "00100", "11111" },
    ["3"] = { "11110", "00001", "00110", "00001", "11110" },
    ["4"] = { "00010", "00110", "01010", "11111", "00010" },
    ["5"] = { "11111", "10000", "11110", "00001", "11110" },
    ["6"] = { "00110", "01000", "11110", "10001", "01110" },
    ["7"] = { "11111", "00010", "00100", "01000", "01000" },
    ["8"] = { "01110", "10001", "01110", "10001", "01110" },
    ["9"] = { "01110", "10001", "01111", "00010", "01100" },
}

local function drawBigScore(score, topY)
    local text = tostring(score)
    local pixelW = 1
    local letterW = 5 * pixelW
    local gap = pixelW
    local totalW = #text * letterW + (#text - 1) * gap
    local startX = math.max(playLeft, math.floor((w - totalW) / 2) + 1)

    local x = startX
    for i = 1, #text do
        local pattern = DIGIT_FONT[text:sub(i, i)]
        if pattern then
            for row = 1, 5 do
                local line = pattern[row]
                for col = 1, 5 do
                    if line:sub(col, col) == "1" then
                        term.setBackgroundColor(colors.white)
                        term.setCursorPos(x + (col - 1) * pixelW, topY + row - 1)
                        term.write(" ")
                    end
                end
            end
        end
        x = x + letterW + gap
    end
end

-- === HUD ===
local function drawHeader(lives)
    fillArea(2, 2, w - 1, playTop - 1, colors.black)
    for i = 1, w - 2 do
        term.setBackgroundColor(colors.yellow)
        term.setCursorPos(1 + i, 2)
        term.write(" ")
    end
    local title = "ROCKET RUNNER"
    local tx = math.floor((w - #title) / 2) + 1
    for i = 1, #title do
        local fg = (i == 1 or i == 7) and colors.red or colors.black
        term.setBackgroundColor(colors.yellow)
        term.setTextColor(fg)
        term.setCursorPos(tx + i - 1, 2)
        term.write(title:sub(i, i))
    end

    local livesText = string.rep("<3", lives)
    local lx = w - #livesText - 2
    fillArea(lx - 1, 3, w - 2, 3, colors.white)
    term.setTextColor(colors.red)
    term.setCursorPos(lx, 3)
    term.write(livesText)
end

-- === ETAT DU JEU ===
local function newGame()
    initClouds()
    return {
        player = { x = math.floor((playLeft + playRight) / 2), y = groundStandY, vy = 0, grounded = true, facing = 1, walkFrame = 0 },
        enemies = {},
        coin = nil,
        score = 0,
        lives = 3,
        invincibleUntil = 0,
        tick = 0,
        gameOver = false,
    }
end

local function now() return os.clock() end
local function isInvincible(state) return now() < state.invincibleUntil end

local function spawnEnemy(state)
    local fromLeft = (math.random(2) == 1)
    table.insert(state.enemies, {
        x = fromLeft and playLeft or playRight,
        y = groundTop - ENEMY_H,
        dir = fromLeft and 1 or -1,
    })
end

local function spawnCoinIfNeeded(state)
    if state.coin then return end
    -- avec JUMP_VELOCITY=-4 et GRAVITY=1, le saut monte au maximum
    -- d'environ 4 cellules : on garde les pieces dans cette portee
    local maxHeight = math.abs(JUMP_VELOCITY) - 1
    local minY = math.max(playTop + 1, groundStandY - maxHeight)
    local maxY = groundStandY - 1
    state.coin = { x = math.random(playLeft + 2, playRight - 2), y = math.random(minY, maxY) }
end

-- === BOITES DE COLLISION ===
local function playerBox(state)
    local p = state.player
    return p.x - math.floor(PLAYER_W / 2), p.y, p.x + math.floor(PLAYER_W / 2), p.y + PLAYER_H - 1
end

local function overlap(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2)
    return ax1 <= bx2 and ax2 >= bx1 and ay1 <= by2 and ay2 >= by1
end

-- === DESSIN DU PERSONNAGE (visage detaille, oreilles, animation de marche) ===
local function drawPlayer(state)
    local p = state.player
    local bg = isInvincible(state) and colors.yellow or colors.white
    local x1, y1, x2, y2 = playerBox(state)

    fillArea(x1, y1, x2, y2, bg)

    -- oreilles (coins du haut, teinte differente)
    term.setBackgroundColor(colors.lightGray)
    term.setCursorPos(x1, y1); term.write(" ")
    term.setCursorPos(x2, y1); term.write(" ")

    -- yeux (ligne du milieu)
    term.setBackgroundColor(bg)
    term.setTextColor(colors.black)
    term.setCursorPos(p.x - 1, y1 + 1)
    term.write("o o")

    -- bouche / animation de marche (ligne du bas)
    term.setCursorPos(p.x, y2)
    if not p.grounded then
        term.write(p.vy < 0 and "^" or "v") -- saute / retombe
    elseif p.walkFrame == 0 then
        term.write("-")
    else
        term.write("~")
    end
end

local function drawEnemy(e)
    fillArea(e.x - 1, e.y, e.x + 1, e.y + ENEMY_H - 1, colors.purple)
    term.setTextColor(colors.black)
    term.setCursorPos(e.x - 1, e.y)
    term.write("^ ^")
end

local function drawCoin(coin, tick)
    local sparkle = (tick % 4 < 2)
    term.setBackgroundColor(sparkle and colors.yellow or colors.orange)
    term.setTextColor(sparkle and colors.orange or colors.yellow)
    term.setCursorPos(coin.x, coin.y)
    term.write("o")
end

local function draw(state, borderPhase)
    drawStripedBorder(borderPhase)
    updateClouds()
    drawScenery()
    drawBigScore(state.score, playTop + 1)

    if state.coin then drawCoin(state.coin, state.tick) end
    for _, e in ipairs(state.enemies) do drawEnemy(e) end
    drawPlayer(state)
    drawHeader(state.lives)
end

-- === LOGIQUE / PHYSIQUE ===
local function loseLife(state)
    if isInvincible(state) then return end
    state.lives = state.lives - 1
    state.invincibleUntil = now() + INVINCIBLE_TIME
    sfxHit()
    if state.lives <= 0 then
        state.gameOver = true
    end
end

local function jump(state)
    if state.player.grounded then
        state.player.vy = JUMP_VELOCITY
        state.player.grounded = false
        sfxJump()
    end
end

local function stepGame(state)
    state.tick = state.tick + 1
    local p = state.player

    -- gravite (le personnage ne vole jamais : toujours tire vers le bas)
    p.vy = math.min(MAX_FALL_SPEED, p.vy + GRAVITY)
    p.y = p.y + (p.vy > 0 and 1 or (p.vy < 0 and -1 or 0))

    if p.y >= groundStandY then
        p.y = groundStandY
        p.vy = 0
        p.grounded = true
    else
        p.grounded = false
    end
    if p.y < playTop then p.y = playTop; if p.vy < 0 then p.vy = 0 end end

    -- spawns
    if state.tick % SPAWN_ENEMY_EVERY == 0 then spawnEnemy(state) end
    if state.tick % SPAWN_COIN_EVERY == 0 then spawnCoinIfNeeded(state) end

    -- deplacement des ennemis
    local remaining = {}
    local px1, py1, px2, py2 = playerBox(state)

    for _, e in ipairs(state.enemies) do
        e.x = e.x + e.dir
        local keep = (e.x > playLeft - 3 and e.x < playRight + 3)

        if keep and overlap(px1, py1, px2, py2, e.x - 1, e.y, e.x + 1, e.y + ENEMY_H - 1) then
            if p.vy > 0 and py2 <= e.y + 1 then
                -- ecrase par le dessus
                state.score = state.score + 20
                p.vy = STOMP_BOUNCE
                sfxStomp()
                keep = false
            elseif not isInvincible(state) then
                loseLife(state)
            end
        end

        if keep then table.insert(remaining, e) end
    end
    state.enemies = remaining

    -- piece
    if state.coin then
        px1, py1, px2, py2 = playerBox(state)
        if overlap(px1, py1, px2, py2, state.coin.x, state.coin.y, state.coin.x, state.coin.y) then
            state.score = state.score + 10
            state.coin = nil
            sfxCoin()
        end
    end
end

-- === ECRAN DE FIN ===
local function drawGameOver(score)
    term.setBackgroundColor(colors.black)
    term.clear()
    drawStripedBorder(false)
    centerText(math.floor(h / 2) - 1, "GAME OVER", colors.red)
    centerText(math.floor(h / 2), "Score final : " .. score, colors.yellow)
    centerText(math.floor(h / 2) + 2, "Appuie sur A pour rejouer", colors.lightGray)
end

local function readButtons()
    return {
        LEFT = integrator.getInput(BUTTON_SIDES.LEFT),
        RIGHT = integrator.getInput(BUTTON_SIDES.RIGHT),
        A = integrator.getInput(BUTTON_SIDES.A),
    }
end

-- === BOUCLE PRINCIPALE D'UNE PARTIE (~16 FPS, tout dans une seule boucle) ===
local function runGame()
    local state = newGame()
    local prevA = false
    local borderTick = 0

    while not state.gameOver do
        local buttons = readButtons()

        if buttons.LEFT then
            state.player.x = math.max(playLeft + math.floor(PLAYER_W / 2), state.player.x - MOVE_SPEED)
            state.player.facing = -1
            state.player.walkFrame = 1 - state.player.walkFrame
        elseif buttons.RIGHT then
            state.player.x = math.min(playRight - math.floor(PLAYER_W / 2), state.player.x + MOVE_SPEED)
            state.player.facing = 1
            state.player.walkFrame = 1 - state.player.walkFrame
        end

        if buttons.A and not prevA then jump(state) end
        prevA = buttons.A

        stepGame(state)

        borderTick = borderTick + 1
        draw(state, (borderTick % 6) < 3)

        sleep(FRAME_TIME)
    end

    drawGameOver(state.score)

    local prevA2 = integrator.getInput(BUTTON_SIDES.A)
    while true do
        sleep(FRAME_TIME)
        local a = integrator.getInput(BUTTON_SIDES.A)
        if a and not prevA2 then return end
        prevA2 = a
    end
end

-- === PROGRAMME PRINCIPAL ===
if speaker then
    parallel.waitForAny(playMusic, function()
        while true do runGame() end
    end)
else
    while true do runGame() end
end